<?php

namespace app\index\controller;

use app\BaseController;
use app\IndexBaseController;
use think\facade\Db;
use think\facade\fetch;
use think\App;
use think\facade\View;

class Trolley extends IndexBaseController
{
    //继承
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function index()
    {
        return View::fetch('index');
    }

    //购物车列表
    public function list() {
        $user = $this->_user;
        $list = Db::name('shopping_trolley')->where(['user_id'=>$user['id'],'deleted'=>0])->select()->toArray();
        return $this->success($list);
    }

    //购物车新增
    public function add() {
        $user = $this->_user;
        $param = $this->_param;
        $cart_goods = Db::name('shopping_trolley')->where(['goods_id'=>$param['goods_id'],'user_id'=>$user['id'],'deleted'=>0])->find();
        if($cart_goods) {
            $res = Db::name('shopping_trolley')->where(['id'=>$cart_goods['id']])->inc("num",$param['num'])->update();
        }else {
            $data = [
                'goods_id' => $param['goods_id'],
                'user_id' => $user['id'],
                'num' => $param['num'],
                'create_time' => time(),
                'update_time' => time()
            ];
            $res = Db::name('shopping_trolley')->insert($data);
        }

        return $this->success($res);
    }

    //购物车编辑
    public function edit() {
        $user = $this->_user;
        $param = $this->_param;
        $data = [
            'goods_id' => $param['goods_id'],
            'user_id' => $user['id'],
            'num' => $param['num'],
            'update_time' => time()
        ];
        $res = Db::name('shopping_trolley')->where(['id'=>$param['id'],'user_id'=>$user['id']])->update($data);
        return $this->success($res);
    }

    //购物车删除
    public function del() {
        $user = $this->_user;
        $param = $this->_param;
        $data = [
            'deleted' => 1,
            'delete_time' => time()
        ];
        $res = Db::name('shopping_trolley')->where(['id'=>$param['id'],'user_id'=>$user['id']])->update($data);
        return $this->success($res);
    }

    //购物车清空
    public function recharge() {

        return $this->success();
    }

}
